
const { readBody } = require('./utils.js');
const { parse } = require('es-module-lexer'); //解析import语法
const MagicString = require('magic-string');

function rewriteImports(source) {
    const imports = parse(source)[0];
    let magicString = new MagicString(source);
    if (imports.length) {
        for (let i = 0; i < imports.length; i++) {
            let { s, e } = imports[i];
            let id = source.substring(s, e)
            if (/^[^\/\.]/.test(id)) {
                //.或者\ 不需要重写
                id = `/@modules/${id}`
                magicString.overwrite(s, e, id)
            }
        }
    }
    return magicString.toString()
    // console.log(imports)
}

/**
 * 接收函数
 * @param {app } param0 当前koa实例
 * @param {root } param1 root 对象
 */
const moduleRewritePlugin = ({ app, root }) => {
    app.use(async (ctx, next) => {
        await next()
        if (ctx.body && ctx.response.is('js')) {
            const content = await readBody(ctx.body);
            const result = rewriteImports(content);
            ctx.body = result
        }

    })
}

module.exports = moduleRewritePlugin;